package cn.tx.controller;

import cn.tx.user.feign.client.UserClient;
import cn.tx.user.feign.fallback.UserClientFallBack;
import cn.tx.user.feign.sentinel.UserBlockHandler;
import cn.tx.pojo.domain.Order;
import cn.tx.pojo.domain.User;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private UserClient userService;

    @Value("${test.name}")
    private String testName;
    @GetMapping("/getOrderById/{id}")
    public Order getOrderById2(@PathVariable("id") Long id) {
        return new Order(id,"202211241130888","姜雪宁","15010089114","花果山水帘洞"+testName);
    }

    @GetMapping("/getUserById/{id}")
    @SentinelResource(value = "getById" ,
            blockHandler = "getByIdBlockHandler",
            blockHandlerClass = UserBlockHandler.class,
            fallback = "getByIdFallback",
    fallbackClass = UserClientFallBack.class)
    public User getUserById(@PathVariable("id") Long id) {
        int i = 1 / new Random().nextInt(2);
        System.out.println(i);
        return userService.getUserById(id);
    }

// 限流方法
//    // 参数必须加上BlockException 不然报错
//    public User getByIdBlockHandler(@PathVariable("id") Long id, BlockException e) {
//        e.printStackTrace();
//        return new User(-1L,"限流","限流限流");
//    }
// 熔断方法
//    public User getByIdFallback(@PathVariable("id") Long id, Throwable e) {
//        return new User(-1L,"熔断","熔断");
//    }

    @GetMapping("/getListOrder")
    public List<Order> getListOrder(@RequestParam Map<String, Object> params) {
        List<Order> orderList = new ArrayList<>();
        Order order1 = new Order(1L,"202211241130888","姜雪宁1","15010089111","花果山水帘洞1"+testName);
        Order order2 = new Order(2L,"202211241130889","姜雪宁2","15010089112","花果山水帘洞2"+testName);
        orderList.add(order1);
        orderList.add(order2);
        return orderList;
    }

}
